<!-- pages/Register.vue -->
<template>
  <div class="register">
    <div class="header">
      <router-link to="/" class="back-home">回到首页</router-link>
    </div>
    <div class="register-form">
      <h2>注册</h2>
      <form @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="email">邮箱 <span class="required">*</span></label>
          <input type="email" id="email" v-model="email" required />
          <p v-if="emailError" class="error">{{ emailError }}</p>
        </div>
        <div class="form-group">
          <label for="account">账号 <span class="required">*</span></label>
          <input type="account" id="account" v-model="account" required />
          <p v-if="accountError" class="error">{{ accountError }}</p>
        </div>
        <div class="form-group">
          <label for="nickName">昵称 <span class="required">*</span></label>
          <input type="nickName" id="nickName" v-model="nickName" required />
          <p v-if="nickNameError" class="error">{{ nickNameError }}</p>
        </div>
        <div class="form-group">
          <label for="password">密码 <span class="required">*</span></label>
          <div class="password-input">
            <input :type="showPassword ? 'text' : 'password'" id="password" v-model="password" required />
            <el-icon @click="togglePasswordVisibility" class="password-icon">
              <View />
            </el-icon>
          </div>
          <p v-if="passwordError" class="error">{{ passwordError }}</p>
        </div>
        <div class="form-group">
          <label for="confirmPassword">确认密码 <span class="required">*</span></label>
          <div class="password-input">
            <input :type="showPassword ? 'text' : 'password'" id="confirmPassword" v-model="confirmPassword" required />
            <el-icon @click="togglePasswordVisibility" class="password-icon">
              <View />
            </el-icon>
          </div>
          <p v-if="confirmPasswordError" class="error">{{ confirmPasswordError }}</p>
        </div>
        <div class="form-group captcha-group">
          <label for="code">验证码 <span class="required">*</span></label>
          <div class="captcha-input">
            <input type="text" id="code" v-model="code" required />
            <img :src="captchaImage" @click="refreshCaptcha" alt="验证码" class="captcha-image" />
          </div>
        </div>
        <button type="submit">注册</button>
        <p class="login-link">
          已有账号？<router-link to="/login">登录</router-link>
        </p>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref,onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { View } from '@element-plus/icons-vue';
import axios from 'axios';

const router = useRouter();

const email = ref('');
const account = ref('');
const password = ref('');
const confirmPassword = ref('');
const nickName = ref('');
const code = ref('');
const uuid = ref('');

const emailError = ref('');
const accountError = ref('');
const passwordError = ref('');
const nickNameError = ref('');
const confirmPasswordError = ref('');
const captchaImage = ref('');

const showPassword = ref(false); // 控制密码是否显示

// 切换密码显示/隐藏
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const validateEmail = (email: string) => {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return re.test(email);
};

// 获取验证码
const refreshCaptcha = async () => {
  try {
    const response = await axios.get('/api/captchaImage');
    if (response.data.code === 200) {
      captchaImage.value = `data:image/jpeg;base64,${response.data.img}`; // 设置验证码图片
      uuid.value = response.data.uuid; // 存储验证码的唯一标识
    } else {
      console.error('获取验证码失败:', response.data.msg);
    }
  } catch (error) {
    console.error('获取验证码失败:', error);
  }
};

// 初始化时获取验证码
onMounted(() => {
  refreshCaptcha();
});

const handleRegister = async () => {
  // 清除之前的错误信息
  emailError.value = '';
  passwordError.value = '';
  confirmPasswordError.value = '';

  // 验证邮箱
  if (!email.value) {
    emailError.value = '邮箱不能为空';
  } else if (!validateEmail(email.value)) {
    emailError.value = '请输入有效的邮箱地址';
  }

  // 验证账号
  if (!account.value) {
    accountError.value = '账号不能为空';
  } else if (account.value.length < 6) {
    accountError.value = '账号至少需要6个字符';
  }

  // 验证昵称
  if (!nickName.value) {
    nickNameError.value = '昵称不能为空';
  } else if (account.value.length > 6) {
    nickNameError.value = '昵称至多6个字符';
  } else if (account.value.length <= 0) {
    nickNameError.value = '昵称至少1个字符';
  }

  // 验证密码
  if (!password.value) {
    passwordError.value = '密码不能为空';
  } else if (password.value.length < 6) {
    passwordError.value = '密码至少需要6个字符';
  }

  // 验证确认密码
  if (!confirmPassword.value) {
    confirmPasswordError.value = '确认密码不能为空';
  } else if (password.value !== confirmPassword.value) {
    confirmPasswordError.value = '密码不一致';
  }

  // 如果有错误，不进行注册
  if (emailError.value || passwordError.value || confirmPasswordError.value) {
    return;
  }

  // 构造请求数据
  const registerData = {
    username: account.value,
    password: password.value,
    email: email.value,
    nickName: nickName.value,
    code: code.value, // 确保发送验证码
    uuid: uuid.value
  };

  try {
    // 调用后端注册接口
    const response = await axios.post('/api/register', registerData);
    if (response.data.code === 200) {
      // 注册成功，跳转到登录页面
      router.push('/login');
    } else {
      // 注册失败，显示错误信息
      alert(response.data.msg);
    }
  } catch (error) {
    // 处理网络错误
    alert('注册失败，请稍后重试');
  }
};
</script>

<style scoped lang="less">
.header {
  width: 100%;
  padding: 10px 20px;
  position: absolute; /* 绝对定位 */
  top: 0;
  left: 0;
  right: 0;
  z-index: 10; /* 确保在表单之上 */
}

.back-home {
  color: #007bff;
  text-decoration: none;
  font-size: 16px;
  font-weight: bold;
}

.back-home:hover {
  text-decoration: underline;
}

.register {
  display: flex;
  flex-direction: column; /* 设置为列方向 */
  align-items: center;
  justify-content: center; /* 顶部对齐 */
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/login-bg.svg') no-repeat center center fixed;
  background-size: cover;
}

.register-form {
  background: rgba(255, 255, 255, 0.9);
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  width: 300px;
  text-align: center;
}

h2 {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
  text-align: left;
}
/*验证码样式 */
.captcha-group {
  margin-bottom: 15px;
}

.captcha-input {
  display: flex;
  align-items: center;
  gap: 10px;
  /* 输入框和图片之间的间距 */
}

.captcha-image {
  width: 100px;
  /* 验证码图片宽度 */
  height: 40px;
  /* 验证码图片高度 */
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.password-input {
  display: flex;
  align-items: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.password-input input {
  border: none;
  outline: none;
  padding: 8px;
}

.password-icon {
  cursor: pointer;
  color: #909399;
  margin-right: 7px;
}

.password-icon:hover {
  color: #409eff;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.required {
  color: red;
}

input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.error {
  color: red;
  font-size: 12px;
  margin-top: 5px;
}

button {
  width: 100%;
  padding: 10px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

button:hover {
  background-color: #218838;
}

.login-link {
  margin-top: 15px;
  font-size: 14px;
}

.login-link a {
  color: #28a745;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}
</style>
